from flask import Blueprint, request
from flask_cors import CORS
from services.sspai import (
    get_latest_sspai_hotspot_from_db,
    get_recommend_sspai_hotspot_from_db,
    get_latest_sspai_hotspot_from_db_page,
    get_recommend_sspai_hotspot_from_db_page,
)

from blueprints.utils import response_error, response_success, is_page_out_of_bounds

sspai_bp = Blueprint("sspai", __name__, url_prefix="/sspai")

CORS(
    sspai_bp, resources={r"/*": {"origins": "http://localhost:5173", "methods": ["GET"], "supports_credentials": True}}
)

@sspai_bp.route("/latest", methods=["GET"])
def get_sspai_hotspot():
    """
    获取少数派最新数据

    测试地址：http://127.0.0.1:5000/sspai/latest
    """
    # 调用服务层函数获取数据
    result = get_latest_sspai_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)

@sspai_bp.route("/recommend", methods=["GET"])
def get_recommend_sspai_hotspot():
    """
    获取少数派推荐数据

    测试地址：http://127.0.0.1:5000/sspai/recommend
    """
    # 调用服务层函数获取数据
    result = get_recommend_sspai_hotspot_from_db()
    result = [hotspot.to_dict() for hotspot in result]
    return response_success(result)

@sspai_bp.route("/latest/page", methods=["GET"])
def get_sspai_hotspot_page():
    """
    获取少数派最新分页数据

    测试地址：http://127.0.0.1:5000/sspai/latest/page?page=1&page_size=10
    """
    # 获取请求参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    if is_page_out_of_bounds(page, page_size):
        return response_error("page 或 page_size 不合理")

    # 调用服务层函数获取数据
    result = get_latest_sspai_hotspot_from_db_page(page, page_size)
    hotspots = [hotspot.to_dict() for hotspot in result["items"]]
    result["items"] = hotspots
    return response_success(result)

@sspai_bp.route("/recommend/page", methods=["GET"])
def get_recommend_sspai_hotspot_page():
    """
    获取少数派推荐分页数据

    测试地址：http://127.0.0.1:5000/sspai/recommend/page?page=1&page_size=10
    """
    # 获取请求参数
    page = int(request.args.get("page", 1))
    page_size = int(request.args.get("page_size", 10))
    if is_page_out_of_bounds(page, page_size):
        return response_error("page 或 page_size 不合理")

    # 调用服务层函数获取数据
    result = get_recommend_sspai_hotspot_from_db_page(page, page_size)
    hotspots = [hotspot.to_dict() for hotspot in result["items"]]
    result["items"] = hotspots
    return response_success(result)